package com.wj.rpsm.user.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wj.rpsm.user.mapper.AmountMapper;
import com.wj.rpsm.user.mapper.PayMapper;
import com.wj.rpsm.user.pojo.Amount;
import com.wj.rpsm.user.pojo.vo.PageResult;
import com.wj.rpsm.user.pojo.Pay;
import com.wj.rpsm.user.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author WeiJin
 * @version 1.0
 */
@Service
@Transactional
public class PayServiceImpl implements PayService {

    @Autowired
    private PayMapper payMapper;
    @Autowired
    private AmountMapper amountMapper;

    /**
     * 1.新增支付记录 2.查询amount余额 3.没有余额amount新增一条记录 4.有余额判断金额修改余额和isPaied
     *
     * @param pay
     * @return
     */
    @Override
    public Integer insertPay(Pay pay) {
        Integer result = payMapper.insertPay(pay);

        Amount amount = amountMapper.getAmountByRoomIdAndType(pay.getPay_room_id(), pay.getPay_type());
        if (Optional.ofNullable(amount).isPresent()) {
            //更新余额，日期
            amount.setAmount(amount.getAmount() + pay.getPay());
            amount.setAmount_date(pay.getPay_date());
            //存在判断余额修改余额
            if (Math.abs(amount.getAmount()) <= pay.getPay()) {
                //支付金额大于余额修改余额，并把isPaid修改为1（已支付）
                amount.setIsPaied(1);
            }
            result += amountMapper.updateAmountById(amount);
        } else {
            //不存在，amount 新增一条记录
            Amount a = new Amount(null, pay.getPay_room_id(), pay.getPay_type(),
                    pay.getPay_date(), pay.getPay(), 1);
            result += amountMapper.insertAmount(a);

        }
        return result;
    }

    @Override
    public List<Pay> pageOfDetailsByUserId(Integer id) {
        return payMapper.pageOfDetailsByUserId(id);
    }
}
